<template>
    <div style="width: 100%; height: 100%;">
        <div class="header">
            <h3>商品.添加</h3>
            <div>
                <el-link to="/adm/Goods">返回商品列表</el-link>
            </div>
            <div>
                <el-button @click="add()" type="primary" plain>商品上架</el-button>
            </div>
        </div>
        <div class="form-container">
            <div class="image-container">
                <!-- 图片上传区域 -->
                <el-upload class="upload-demo"
                 drag 
                :auto-upload="false" 
                list-type="picture" 
                :show-file-list="true"
                :file-list="fileList" 
                :limit="1" :on-change="onChangeFile">
                	<!-- <div v-show="data.cur==1">
                		<h3>原图片</h3>
                		<el-avatar :size="50" :src="$ip+`/api/public/showing/`+data.user.pic" />
                	</div> -->
                	<h3>新上传的图片</h3>
                	<img v-if="imgUrl" :src="imgUrl" class="avatar"  />
                	<div class="el-upload__text">
                		拖入或者 <em>点击上传</em>
                	</div>
                	<template #tip>
                		<div class="el-upload__tip">
                			图片不能大于 500kb
                		</div>
                	</template>
                </el-upload>
            </div>
            
            <el-form :model="data.goods" :rules="rules" ref="formRef" label-width="120px">
                <el-form-item label="商品序号" prop="bookid">
                    <el-input v-model="data.goods.bookid"></el-input>
                </el-form-item>
                <el-form-item label="商品名称" prop="bookname">
                    <el-input v-model="data.goods.bookname"></el-input>
                </el-form-item>
				
                <el-form-item label="商品原价格"  prop="price">
                    <el-input v-model="data.goods.price" type="number" placeholder="0"></el-input>
                </el-form-item>
                <el-form-item label="商品会员价" prop="vip">
                    <el-input v-model="data.goods.vip" type="number" placeholder="0"></el-input>
                </el-form-item>
                <el-form-item label="店铺" prop="guc">
                    <el-input v-model="data.goods.guc"></el-input>
                </el-form-item>
                <el-form-item label="上架时间"  prop="gdate">
                    <el-date-picker
                        v-model="data.goods.gdate"
                        type="date"
                        placeholder="请选择"
                        :format="displayFormat"
                        :value-format="backendFormat"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="商品库存"  prop="stock">
                    <el-input v-model="data.goods.stock" type="number" placeholder="0"></el-input>
                </el-form-item>
				
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { $get, $postf } from '../../../ajax/index.js';
import myalert from '../../../utils/myalert.js';
import { useRoute, useRouter } from 'vue-router';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import type { UploadProps } from 'element-plus';

const visible = ref(false);
const imageUrl = ref(''); // 图片预览URL
const fileList = ref([]);
const file = ref({});
const imgUrl = ref('');
const router = useRouter(); // 获取路由实例
const data = reactive({
    goods: {
        bookid: '',
        bookname: '',
        gid: '',
        guc: '',
        gdate: '',
        stock: '',
        vip: 0,
        price: 0,
        types: 0,
    },
    types2: [],
    types: [],
    myfile: null, // 存储上传的文件
});
const uploadRef = ref<HTMLElement | null>(null);
const formRef = ref<FormInstance | null>(null);
const uploadUrl = ref('api/adm/upload'); // 后端上传接口地址

const displayFormat = 'YYYY年MM月DD日';
const backendFormat = 'YYYY-MM-DD';

const rules = reactive<FormRules>({
    bookid: [
        { required: true, message: '商品序号不能为空', trigger: 'blur' },
    ],
    bookname: [
        { required: true, message: '商品名称不能为空', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '商品原价格不能为空', trigger: 'blur' },
    ],
    vip: [
        { required: true, message: '商品会员价不能为空', trigger: 'blur' },
    ],
    guc: [
        { required: true, message: '店铺不能为空', trigger: 'blur' },
    ],
    gdate: [
        { required: true, message: '上架时间不能为空', trigger: 'blur' },
    ],
    stock: [
        { required: true, message: '商品库存不能为空', trigger: 'blur' },
    ],
});

const route = useRoute()

// 挂载
onMounted(() => {
    console.log(route.query.id);
    // 如果是编辑商品，加载已有商品信息
    if (route.query.id) {
        $get('/api/adm/goods/findonekid/' + route.query.id)
           .then((resp) => {
                console.log(resp.data.data);
                data.goods = resp.data.data;
                // 如果已有图片，设置图片URL
                if (resp.data.data.gid) {
                    imageUrl.value = resp.data.data.gid; // 假设后端返回的gid是图片URL
                }
            });
    }
    
    // 初始化一级类型
    $get('/api/adm/type/findpid')
       .then((resp) => {
            console.log(resp.data.data);
            if (!Array.isArray(data.types2)) {
                data.types2 = [];
            }
            if (Array.isArray(data.types2) && resp.data.data && Array.isArray(resp.data.data)) {
                resp.data.data.forEach((item) => {
                    data.types2.push(item);
                });
            }
            data.types = resp.data.data;
        });
});
function onChangeFile(file, fileList) {
		console.log("file=" + file)
		console.log("fileList=" + fileList)
		if (fileList.length > 0) {
			//fileList[0].raw; 文件内容
			imgUrl.value = URL.createObjectURL(fileList[0].raw)
			data.myfile=fileList[0].raw;
			console.log(data.myfile);
		}
	}


const add = async () => {
        // 构造表单数据
        const fd = new FormData();
        fd.append('bookid', data.goods.bookid);
        fd.append('bookname', data.goods.bookname);
        fd.append('guc', data.goods.guc);
        fd.append('stock', data.goods.stock);
        fd.append('gdate', data.goods.gdate);
        fd.append('vip', data.goods.vip);
        fd.append('price', data.goods.price);
        fd.append('myfiles', data.myfile);
        // 提交商品信息
            $postf('api/adm/goods/add', fd)
               .then((resp) => {
                    ElMessage.success('商品添加成功');
                })
				router.push('/adm/Goods');//跳转到商品详情
};
</script>

<style>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
    margin-bottom: 20px;
}

.header h3 {
    margin: 0;
}

.form-container {
    display: flex;
    gap: 50px;
}

.image-container {
    width: 25vw;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.upload-demo {
    width: 100%;
    height: 25vh;
    min-height: 200px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.upload-placeholder {
    text-align: center;
    color: #999;
}

.upload-placeholder p {
    margin-top: 10px;
    font-size: 14px;
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
}

.mt-3 {
    margin-top: 15px;
}

.el-form-item__label {
    min-width: 80px;
}
</style>